package com.ljl.ningwei.controller;

import com.ljl.ningwei.domain.CategorylListVO;
import com.ljl.ningwei.domain.MaterialDeleteVO;
import com.ljl.ningwei.domain.MaterialUpdateVO;
import com.ljl.ningwei.entity.Category;
import com.ljl.ningwei.common.event.CategoryDeletedEvent;
import com.ljl.ningwei.common.result.Result;
import com.ljl.ningwei.service.CategoryService;
import com.ljl.ningwei.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 吕佳乐
 * 2025-03-13 20:39
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class CategoryController {

    private final CategoryService categoryService;
    private final ApplicationEventPublisher eventPublisher;
    private final FileService fileService;

    /**
     * 递归获取所有的分类
     *
     * @return
     */
    @RequestMapping("/category/list")
    public Result<List<CategorylListVO>> list() {
        List<CategorylListVO> result;
        try {
            List<Category> categoryList = categoryService.list();
            // 按父ID分组（避免递归中重复遍历）
            Map<Long, List<Category>> parentIdToCategories = categoryList.stream()
                    .collect(Collectors.groupingBy(Category::getParentId));
            // 构建分类树
            result = buildTreeNodes(parentIdToCategories, 0L);
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            log.info("异常: " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success(result);
    }




    @RequestMapping("/category/create")
    public Result<Void> create(@RequestParam("name") String name,
                               @RequestParam("imageUrl") String imageUrl) {
        try {
            categoryService.edit(null, name, imageUrl);
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            log.info("异常: " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    @RequestMapping("/category/update")
    public Result<MaterialUpdateVO> update(@RequestParam("id") Long id,
                                           @RequestParam(value = "name", required = false) String name,
                                           @RequestParam(value = "imageUrl", required = false) String imageUrl) {
        try {
            // 更新成功
            categoryService.edit(id, name, imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            // 或者使用日志框架记录详细信息
            log.info("异常:{} " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    /**
     * 将关联的商品进行异步删除
     * {@link com.ljl.ningwei.service.impl.MaterialServiceImpl#handleCategoryDeletedEvent}
     *
     * @param id
     * @return
     */
    @RequestMapping("/category/delete")
    public Result<MaterialDeleteVO> delete(@RequestParam("id") Long id) {
        try {
            // 1.先删除类目
            categoryService.delete(id);
            // 2.再清理商品(通过商品服务) 异步执行
            eventPublisher.publishEvent(new CategoryDeletedEvent(id));
        } catch (Exception e) {
            // 捕获异常并记录日志
            log.info("异常:{}" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return Result.success();
    }

    private List<CategorylListVO> buildTreeNodes(Map<Long, List<Category>> parentIdToCategories, Long parentId) {
        List<Category> categoryList = parentIdToCategories.getOrDefault(parentId, Collections.emptyList());
        List<CategorylListVO> categorylListVOList = categoryList.stream()
                .map(category -> {
                    CategorylListVO categorylListVO = new CategorylListVO()
                            .setId(category.getId())
                            .setName(category.getName())
                            .setImageUrl(category.getImageUrl())
                            .setParentId(category.getParentId())
                            .setChildrenList(buildTreeNodes(parentIdToCategories, category.getId()));
                    return categorylListVO;
                }).collect(Collectors.toList());
        return categorylListVOList;
    }
}
